const axios = require('axios');

// 测试配置
const NODES = [3001, 3002, 3003];
const BASE_URL = 'http://localhost';

async function testSystem() {
  console.log('🧪 开始测试分布式缓存系统...\n');
  
  try {
    // 测试1: 写入数据到不同节点
    console.log('📤 测试1: 写入数据到不同节点');
    const testData = [
      { key: 'myname', value: '电子科技大学@2023', node: 3001 },
      { key: 'tasks', value: ['task 1', 'task 2', 'task 3'], node: 3002 },
      { key: 'age', value: 123, node: 3003 }
    ];
    
    for (const data of testData) {
      const url = `${BASE_URL}:${data.node}/`;
      const response = await axios.post(url, { [data.key]: data.value });
      console.log(`✅ 写入 ${data.key}=${JSON.stringify(data.value)} 到节点${data.node}:`, response.data);
    }
    
    // 测试2: 从任意节点读取数据
    console.log('\n📥 测试2: 从任意节点读取数据');
    for (const data of testData) {
      for (const port of NODES) {
        const url = `${BASE_URL}:${port}/${data.key}`;
        const response = await axios.get(url);
        console.log(`✅ 从节点${port}读取 ${data.key}:`, response.data);
      }
    }
    
    // 测试3: 更新数据
    console.log('\n🔄 测试3: 更新数据');
    const updateUrl = `${BASE_URL}:3001/`;
    const updateResponse = await axios.post(updateUrl, { age: 999 });
    console.log('✅ 更新 age=999:', updateResponse.data);
    
    // 验证更新
    const verifyUrl = `${BASE_URL}:3002/age`;
    const verifyResponse = await axios.get(verifyUrl);
    console.log('✅ 验证更新结果:', verifyResponse.data);
    
    // 测试4: 删除数据
    console.log('\n🗑️ 测试4: 删除数据');
    for (const data of testData) {
      for (const port of NODES) {
        const url = `${BASE_URL}:${port}/${data.key}`;
        const response = await axios.delete(url);
        console.log(`✅ 从节点${port}删除 ${data.key}:`, response.data);
      }
    }
    
    // 测试5: 验证删除
    console.log('\n🔍 测试5: 验证删除');
    for (const data of testData) {
      for (const port of NODES) {
        const url = `${BASE_URL}:${port}/${data.key}`;
        try {
          await axios.get(url);
          console.log(`❌ 节点${port}上 ${data.key} 仍然存在`);
        } catch (error) {
          if (error.response && error.response.status === 404) {
            console.log(`✅ 节点${port}上 ${data.key} 已删除`);
          }
        }
      }
    }
    
    console.log('\n🎉 所有测试完成！');
    
  } catch (error) {
    console.error('❌ 测试失败:', error.message);
    console.log('\n💡 请确保所有节点已启动:');
    console.log('   Linux/Mac: ./start-servers.sh');
    console.log('   Windows: start-servers.bat');
  }
}

// 如果直接运行此文件
if (require.main === module) {
  testSystem();
}

module.exports = { testSystem };
